class WebRTCConnection {
    constructor(signaling) {
        this.peerConnection = null
        this.signaling = signaling // 信令服务器连接实例
        this.dataChannel = null
        this.init()
    }

    init() {
        // 初始化 RTCPeerConnection
        this.peerConnection = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' }
            ]
        })

        // 设置事件监听
        this.setupEventListeners()
    }

    setupEventListeners() {
        // ICE 候选者处理
        this.peerConnection.onicecandidate = ({ candidate }) => {
            if (candidate) {
                this.signaling.send({
                    type: 'ice-candidate',
                    candidate
                })
            }
        }

        // 连接状态变化
        this.peerConnection.onconnectionstatechange = () => {
            console.log('连接状态:', this.peerConnection.connectionState)
        }

        // 数据通道接收
        this.peerConnection.ondatachannel = (event) => {
            const dataChannel = event.channel
            this.setupDataChannel(dataChannel)
        }
    }

    // 检查设备支持情况
    static async checkDeviceSupport() {
        try {
            const devices = await navigator.mediaDevices.enumerateDevices();
            const hasCamera = devices.some(device => device.kind === 'videoinput');
            const hasMicrophone = devices.some(device => device.kind === 'audioinput');

            return {
                camera: hasCamera,
                microphone: hasMicrophone
            };
        } catch (error) {
            console.error('检查设备支持失败:', error);
            return {
                camera: false,
                microphone: false
            };
        }
    }
    // 创建数据通道
    createDataChannel() {
        this.dataChannel = this.peerConnection.createDataChannel('messageChannel')
        this.setupDataChannel(this.dataChannel)
    }

    // 设置数据通道事件
    setupDataChannel(dataChannel) {
        dataChannel.onopen = () => {
            console.log('数据通道已打开')
        }

        dataChannel.onmessage = (event) => {
            console.log('收到消息:', event.data)
        }

        dataChannel.onclose = () => {
            console.log('数据通道已关闭')
        }
    }

    // 发起方：创建并发送 offer
    async initiateConnection() {
        try {
            this.createDataChannel()
            const offer = await this.peerConnection.createOffer()
            await this.peerConnection.setLocalDescription(offer)

            this.signaling.send({
                type: 'offer',
                offer
            })
        } catch (error) {
            console.error('发起连接失败:', error)
        }
    }

    // 接收方：处理 offer 并发送 answer
    async handleOffer(offer) {
        try {
            await this.peerConnection.setRemoteDescription(new RTCSessionDescription(offer))
            const answer = await this.peerConnection.createAnswer()
            await this.peerConnection.setLocalDescription(answer)

            this.signaling.send({
                type: 'answer',
                answer
            })
        } catch (error) {
            console.error('处理 offer 失败:', error)
        }
    }

    // 处理 answer
    async handleAnswer(answer) {
        try {
            await this.peerConnection.setRemoteDescription(new RTCSessionDescription(answer))
        } catch (error) {
            console.error('处理 answer 失败:', error)
        }
    }

    // 处理 ICE candidate
    async handleIceCandidate(candidate) {
        try {
            await this.peerConnection.addIceCandidate(new RTCIceCandidate(candidate))
        } catch (error) {
            console.error('添加 ICE candidate 失败:', error)
        }
    }

    // 发送消息
    sendMessage(message) {
        if (this.dataChannel && this.dataChannel.readyState === 'open') {
            this.dataChannel.send(message)
        }
    }
}

export default WebRTCConnection